package com.ly.util;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;

/**
 * @author 李岩
 * @date 2021/12/31-9:21
 * @describe
 */
public class ALiPayUtil {


    public static void  getALiPay(HttpServletResponse response, Integer orderId, BigDecimal cost, String loginName, String userAddress,String return_url) throws Exception {

        System.out.println("进入了alipay");
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = String.valueOf(orderId);
        //付款金额，必填
        String total_amount = String.valueOf(cost);
        //订单名称，必填
        String subject = loginName+userAddress;
        //商品描述，可空
        String body = null;

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        System.out.println("支付----------------");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        response.setContentType("text/html; charset=utf-8");
        response.getWriter().write(result);
    }
}
